package com.example.rae.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/redisson")
public class RedissonController {
    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/test")
    public void test() {
        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    RLock lock = redissonClient.getLock("anyLock");
//                                        lock.lock();
//                    System.out.println("在%s线程中加锁\n" + Thread.currentThread());
//                    lock.unlock();

//                    lock.lock(10, TimeUnit.SECONDS);
//                    System.out.printf("在%s线程中加锁,10秒自动解锁\n", Thread.currentThread());
                    try {
                        boolean res = lock.tryLock(20, 10, TimeUnit.SECONDS);
                        if (res) {
                            System.out.println("在%s线程中加锁\n" + Thread.currentThread());
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }).start();
        }
    }

    @GetMapping("/test1")
    public void test1() {
        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    RLock lockName = redissonClient.getLock("lockName");
                    lockName.lock(10, TimeUnit.SECONDS);
                    System.out.printf("在%s线程中加锁,如果未被释放10秒自动释放\n", Thread.currentThread());
                    lockName.unlock();
                    System.out.printf("在%s线程中释放锁\n", Thread.currentThread());
                }
            }).start();
        }
    }
}
